package org.rupa.core.register;

import org.rupa.common.constant.HeartbeatConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 心跳机制客户端
 */
public abstract class AbstractRegisterHeartbeatClient implements Register, ApplicationContextAware {
    protected final Logger log = LoggerFactory.getLogger(AbstractRegisterHeartbeatClient.class);

    protected long serverLashUpdateTime = 0;

    protected ApplicationContext context;

    protected ScheduledExecutorService executorService;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.context = applicationContext;
    }

    protected void startHeartbeatDetection() {
        executorService = Executors.newScheduledThreadPool(1);
        executorService.scheduleWithFixedDelay(
                new HeartbeatDetection(),
                0,
                10,
                TimeUnit.SECONDS
        );
    }

    private class HeartbeatDetection implements Runnable {
        @Override
        public void run() {
            refreshHeartbeat();

            if (serverLashUpdateTime != 0 && (System.currentTimeMillis() - serverLashUpdateTime) > HeartbeatConstant.TIME_OUT) {
                // 服务器宕机
                close("服务器宕机");
            }
        }
    }

    protected abstract void register();
    protected abstract void unregister();
    protected abstract void refreshHeartbeat();
    protected abstract void close(String msg);
}
